package handling.channel.handler;

import client.MapleCharacter;
import client.MapleClient;
import handling.channel.ChannelServer;
import handling.world.World.Alliance;
import handling.world.World.Find;
import handling.world.World.Guild;
import handling.world.guild.MapleGuild;
import handling.world.guild.MapleGuildResponse;
import tools.FileoutputUtil;
import tools.MaplePacketCreator;
import tools.data.LittleEndianAccessor;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

public class GuildHandler {
    private static List<Invited> invited;
    private static long nextPruneTime;

    public static void denyGuildRequest(String from, MapleClient c) {
        MapleCharacter cfrom = c.getChannelServer().getPlayerStorage().getCharacterByName(from);
        if (cfrom != null) {
            cfrom.getClient().sendPacket(MaplePacketCreator.denyGuildInvitation(c.getPlayer().getName()));
        }
    }

    private static boolean isGuildNameAcceptable(String name) {
        return name.length() <= 15 && name.length() >= 3;
    }

    private static void respawnPlayer(MapleCharacter mc) {
        mc.getMap().broadcastMessage(mc, MaplePacketCreator.removePlayerFromMap(mc.getId()), false);
        mc.getMap().broadcastMessage(mc, MaplePacketCreator.spawnPlayerMapobject(mc), false);
    }

    private static void SaveCharDb(MapleCharacter c) {
        try {
            c.saveToDB(false, false);
        } catch (Exception e) {
            System.out.println("公会的错误:" + e);
            FileoutputUtil.logToFile("logs/公会存档保存数据异常.txt", "\r\n " + FileoutputUtil.NowTime() + " IP: " + c.getClient().getSession().remoteAddress().toString().split(":")[0] + " 账号 " + c.getClient().getAccountName() + " 账号ID " + c.getClient().getAccID() + " 角色名 " + c.getName() + " 角色ID " + c.getId());
            FileoutputUtil.outError("logs/公会存档保存数据异常.txt", (Throwable) e);
        }
    }

    public static void HandleGuild(LittleEndianAccessor slea, MapleClient c) {
        if (System.currentTimeMillis() >= GuildHandler.nextPruneTime) {
            Iterator<Invited> itr = GuildHandler.invited.iterator();
            while (itr.hasNext()) {
                Invited inv = (Invited) itr.next();
                if (System.currentTimeMillis() >= inv.expiration) {
                    itr.remove();
                }
            }
            GuildHandler.nextPruneTime = System.currentTimeMillis() + 1200000L;
        }
        GuildOperation operation = GuildOperation.getByValue(slea.readByte());
        if (operation == null) {
            return;
        }
        switch (operation) {
            case CREATE: {
                int cost = 1500000;
                if (c.getPlayer().getGuildId() > 0 || c.getPlayer().getMapId() != 200000301) {
                    c.getPlayer().dropMessage(1, "无法建立公会\r\n已经有公会或不在英雄之殿");
                    return;
                }
                if (c.getPlayer().getMeso() < cost) {
                    c.getPlayer().dropMessage(1, "你沒有足够的金币建立公会。目前建立公会需要: " + cost + " 的金币。");
                    return;
                }
                String guildName = slea.readMapleAsciiString();
                if (!isGuildNameAcceptable(guildName)) {
                    c.getPlayer().dropMessage(1, "这个公会名称是不被准许的.");
                    return;
                }
                int guildId = Guild.createGuild(c.getPlayer().getId(), guildName);
                if (guildId == 0) {
                    c.sendPacket(MaplePacketCreator.genericGuildMessage((byte) 28));
                    return;
                }
                c.getPlayer().gainMeso(-cost, true, false, true);
                c.getPlayer().setGuildId(guildId);
                c.getPlayer().setGuildRank((byte) 1);
                c.getPlayer().saveGuildStatus();
                Guild.setGuildMemberOnline(c.getPlayer().getMGC(), true, c.getChannel());
                c.sendPacket(MaplePacketCreator.showGuildInfo(c.getPlayer()));
                Guild.gainGP(c.getPlayer().getGuildId(), 500);
                Guild.setGuildMemberOnline(c.getPlayer().getMGC(), true, c.getChannel());
                c.getPlayer().dropMessage(1, "恭喜你成功创建一个公会.");
                respawnPlayer(c.getPlayer());
                break;
            }
            case INVITE: {
                if (c.getPlayer().getGuildId() <= 0 || c.getPlayer().getGuildRank() > 2) {
                    return;
                }
                String playerName = slea.readMapleAsciiString();
                MapleGuildResponse mgr = MapleGuild.sendInvite(c, playerName);
                if (mgr != null) {
                    c.sendPacket(mgr.getPacket());
                    break;
                }
                Invited inv2 = new Invited(playerName, c.getPlayer().getGuildId());
                if (!GuildHandler.invited.contains(inv2)) {
                    GuildHandler.invited.add(inv2);
                }
                break;
            }
            case ACCEPTED: {
                if (c.getPlayer().getGuildId() > 0) {
                    return;
                }
                int guildId2 = slea.readInt();
                int cid = slea.readInt();
                if (cid != c.getPlayer().getId()) {
                    return;
                }
                String playerName2 = c.getPlayer().getName().toLowerCase();
                Iterator<Invited> itr2 = GuildHandler.invited.iterator();
                while (itr2.hasNext()) {
                    Invited inv3 = (Invited) itr2.next();
                    if (guildId2 == inv3.gid && playerName2.equals(inv3.name)) {
                        c.getPlayer().setGuildId(guildId2);
                        c.getPlayer().setGuildRank((byte) 5);
                        itr2.remove();
                        int s = Guild.addGuildMember(c.getPlayer().getMGC());
                        if (s == 0) {
                            c.getPlayer().dropMessage(1, "你想要加入的公会已经满了.");
                            c.getPlayer().setGuildId(0);
                            return;
                        }
                        c.sendPacket(MaplePacketCreator.showGuildInfo(c.getPlayer()));
                        MapleGuild gs = Guild.getGuild(guildId2);
                        for (byte[] pack : Alliance.getAllianceInfo(gs.getAllianceId(), true)) {
                            if (pack != null) {
                                c.sendPacket(pack);
                            }
                        }
                        c.getPlayer().saveGuildStatus();
                        respawnPlayer(c.getPlayer());
                        break;
                    }
                }
                break;
            }
            case LEAVING: {
                int cid2 = slea.readInt();
                String name = slea.readMapleAsciiString();
                if (cid2 != c.getPlayer().getId() || !name.equals(c.getPlayer().getName()) || c.getPlayer().getGuildId() <= 0) {
                    return;
                }
                if (c.getPlayer().getMapId() == 990001000) {
                    c.getPlayer().dropMessage(5, "无法在当前地图退出工会。");
                    return;
                }
                Guild.leaveGuild(c.getPlayer().getMGC());
                c.sendPacket(MaplePacketCreator.showGuildInfo(null));
                break;
            }
            case EXPEL: {
                int cid2 = slea.readInt();
                String name = slea.readMapleAsciiString();
                MapleCharacter victim = null;
                int ch = Find.findChannel(name);
                if (ch >= 1) {
                    victim = ChannelServer.getInstance(ch).getPlayerStorage().getCharacterByName(name);
                    if (victim != null && victim.getMapId() == 990001000) {
                        c.getPlayer().dropMessage(5, "当前无法驅除" + victim.getName() + "工会。");
                        return;
                    }
                }
                if (c.getPlayer().getGuildRank() > 2 || c.getPlayer().getGuildId() <= 0) {
                    return;
                }
                Guild.expelMember(c.getPlayer().getMGC(), name, cid2);
                break;
            }
            case CHANGE_RANK_TITLE: {
                if (c.getPlayer().getGuildId() <= 0 || c.getPlayer().getGuildRank() != 1) {
                    return;
                }
                String[] ranks = new String[5];
                for (int i = 0; i < 5; ++i) {
                    ranks[i] = slea.readMapleAsciiString();
                }
                Guild.changeRankTitle(c.getPlayer().getGuildId(), ranks);
                break;
            }
            case CHANGE_RANK: {
                int cid2 = slea.readInt();
                byte newRank = slea.readByte();
                if (newRank <= 1 || newRank > 5 || c.getPlayer().getGuildRank() > 2 || (newRank <= 2 && c.getPlayer().getGuildRank() != 1) || c.getPlayer().getGuildId() <= 0) {
                    return;
                }
                Guild.changeRank(c.getPlayer().getGuildId(), cid2, (int) newRank);
                break;
            }
            case CHANGE_EMBLEM: {
                if (c.getPlayer().getGuildId() <= 0 || c.getPlayer().getGuildRank() != 1 || c.getPlayer().getMapId() != 200000301) {
                    return;
                }
                if (c.getPlayer().getMeso() < 1000000) {
                    c.getPlayer().dropMessage(1, "你的金币不够,无法创建公会徽章");
                    return;
                }
                short bg = slea.readShort();
                byte bgcolor = slea.readByte();
                short logo = slea.readShort();
                byte logocolor = slea.readByte();
                Guild.setGuildEmblem(c.getPlayer().getGuildId(), bg, bgcolor, logo, logocolor);
                c.getPlayer().gainMeso(-1000000, true, false, true);
                respawnPlayer(c.getPlayer());
                break;
            }
            case CHANGE_NOTICE: {
                String notice = slea.readMapleAsciiString();
                if (notice.length() > 100 || c.getPlayer().getGuildId() <= 0 || c.getPlayer().getGuildRank() > 2) {
                    return;
                }
                Guild.setGuildNotice(c.getPlayer().getGuildId(), notice);
                break;
            }
        }
    }

    static {
        invited = new LinkedList();
        nextPruneTime = System.currentTimeMillis() + 1200000L;
    }

    private enum GuildOperation {
        CREATE((byte) 2),
        INVITE((byte) 5),
        ACCEPTED((byte) 6),
        LEAVING((byte) 7),
        EXPEL((byte) 8),
        CHANGE_RANK_TITLE((byte) 13),
        CHANGE_RANK((byte) 14),
        CHANGE_EMBLEM((byte) 15),
        CHANGE_NOTICE((byte) 16);

        byte value;

        private GuildOperation(byte op) {
            this.value = op;
        }

        public static GuildOperation getByValue(byte value) {
            for (GuildOperation op : values()) {
                if (op.value == value) {
                    return op;
                }
            }
            return null;
        }
    }

    private static class Invited {
        public String name;
        public int gid;
        public long expiration;

        public Invited(String n, int id) {
            this.name = n.toLowerCase();
            this.gid = id;
            this.expiration = System.currentTimeMillis() + 3600000L;
        }

        @Override
        public boolean equals(Object other) {
            if (!(other instanceof Invited)) {
                return false;
            }
            Invited oth = (Invited) other;
            return this.gid == oth.gid && this.name.equals(oth.name);
        }

        @Override
        public int hashCode() {
            int hash = 3;
            hash = 67 * hash + Objects.hashCode(this.name);
            hash = 67 * hash + this.gid;
            return hash;
        }
    }
}
